package cn.zyq.demo.service.sys.impl;


import cn.hutool.core.convert.Convert;
import cn.zyq.demo.beans.sys.SysAdmin;
import cn.zyq.demo.beans.sys.SysConfig;
import cn.zyq.demo.mapper.sys.SysConfigMapper;
import cn.zyq.demo.service.sys.SysConfigService;
import cn.zyq.demo.system.common.BaseService;
import cn.zyq.demo.system.common.PageParam;
import cn.zyq.demo.system.config.redis.RedisService;
import cn.zyq.demo.system.ry.CacheConstants;
import cn.zyq.demo.system.ry.UserConstants;
import cn.zyq.demo.system.ry.util.SecurityUtils;
import cn.zyq.demo.system.ry.util.StringUtils;
import com.aliyun.oss.ServiceException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;

/**
 * 参数配置表
 * 2023-05-12 20:14:08
 */

@Slf4j
@Service
public class SysConfigServiceImpl extends BaseService implements SysConfigService {
    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private RedisService redisCache;

    @Override
    public PageInfo<SysConfig> list(PageParam pageParam, SysAdmin admin) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        List<SysConfig> dbList = this.sysConfigMapper.list(pageParam.getKv());
        return new PageInfo<>(dbList);
    }

    @Override
    public void add(SysConfig param, SysAdmin admin) {
        this.setCreateBaseData(param, admin);
        this.sysConfigMapper.insertSelective(param);
    }

    @Override
    public void update(SysConfig param, SysAdmin admin) {
        Integer id = param.getSysConfigID();
        this.setUpdateBaseData(param, admin);
        this.sysConfigMapper.updateByPrimaryKeySelective(param);
    }

    @Override
    public void del(String serviceID, SysAdmin admin) {
        SysConfig dbInfo = this.detail(serviceID);
        Integer id = dbInfo.getSysConfigID();
        this.deleteLogic(id, admin, this.sysConfigMapper);
    }

    @Override
    public SysConfig detail(String serviceID, SysAdmin admin) {
        return this.detail(serviceID);
    }

    @Override
    public SysConfig detail(String serviceID) {
        SysConfig dbInfo = this.getByServiceID(serviceID, SysConfig.class, this.sysConfigMapper);
        this.checkLogicExist(dbInfo);
        return dbInfo;
    }

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init() {
        loadingConfigCache();
    }

    /**
     * 查询参数配置信息
     *
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    public SysConfig selectConfigById(Integer configId) {
        return sysConfigMapper.selectByPrimaryKey(configId);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        SysConfig retConfig = sysConfigMapper.selectOne(config);
        if (StringUtils.isNotNull(retConfig)) {
            redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaEnabled() {
        String captchaEnabled = selectConfigByKey("sys.account.captchaEnabled");
        if (StringUtils.isEmpty(captchaEnabled)) {
            return true;
        }
        return Convert.toBool(captchaEnabled);
    }

    /**
     * 查询参数配置列表
     *
     * @param param 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<SysConfig> selectConfigList(PageParam param) {
        return sysConfigMapper.list(param.getKv());
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(SysConfig config) {
        this.setCreateBaseData(config, SecurityUtils.getLoginUser().getSysAdmin());
        int row = sysConfigMapper.insertSelective(config);
        if (row > 0) {
            redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(SysConfig config) {
        SysConfig temp = sysConfigMapper.selectByPrimaryKey(config.getSysConfigID());
        if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) {
            redisCache.deleteObject(getCacheKey(temp.getConfigKey()));
        }
        this.setUpdateBaseData(config, SecurityUtils.getLoginUser().getSysAdmin());
        int row = sysConfigMapper.updateByPrimaryKeySelective(config);
        if (row > 0) {
            redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     */
    @Override
    public void deleteConfigByIds(Integer[] configIds) {
        for (Integer configId : configIds) {
            SysConfig config = selectConfigById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
                throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
            sysConfigMapper.deleteByPrimaryKey(configId);
            redisCache.deleteObject(getCacheKey(config.getConfigKey()));
        }
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {
        List<SysConfig> configsList = sysConfigMapper.selectAll();
        for (SysConfig config : configsList) {
            redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache() {
        Collection<String> keys = redisCache.keys(CacheConstants.SYS_CONFIG_KEY + "*");
        redisCache.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyUnique(SysConfig config) {
        Integer configId = StringUtils.isNull(config.getSysConfigID()) ? -1 : config.getSysConfigID();
        SysConfig info = this.getByKey(config.getConfigKey());
        if (StringUtils.isNotNull(info) && !info.getSysConfigID().equals(configId) ) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    private SysConfig getByKey(String configKey){
        SysConfig param = new SysConfig();
        param.setConfigKey(configKey);
        param.setDeleted(0);
        List<SysConfig> select = this.sysConfigMapper.select(param);
        if (CollectionUtils.isNotEmpty(select)){
            return select.get(0);
        }
        return null;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }
}
